import React, { useEffect, useState } from "react";
import { TreeSelect, Spin, Tag } from "antd";
import type { TreeSelectProps } from "antd/es/tree-select";
import "./style.less";

// 组织/部门/人员节点类型
export interface OrgTreeNode {
  id: string;
  parentId?: string;
  title: string;
  type: "org" | "department" | "user";
  value: string;
  key: string;
  isLeaf?: boolean;
  disabled?: boolean;
  children?: OrgTreeNode[];
  // 用户特有字段
  avatar?: string;
  position?: string;
  email?: string;
}

export interface OrganizationTreeSelectProps
  extends Omit<TreeSelectProps<string | string[]>, "treeData" | "loadData"> {
  /**
   * 组织根节点数据加载函数
   */
  fetchRootData?: () => Promise<OrgTreeNode[]>;
  /**
   * 异步加载子节点数据的函数
   */
  loadChildrenData?: (node: OrgTreeNode) => Promise<OrgTreeNode[]>;
  /**
   * 是否显示用户信息
   */
  showUserInfo?: boolean;
  /**
   * 是否只能选择用户（不能选择组织/部门）
   */
  userOnly?: boolean;
  /**
   * 初始数据
   */
  initialData?: OrgTreeNode[];
  /**
   * 组件加载状态
   */
  loading?: boolean;
  /**
   * 是否启用异步加载
   * @default false
   */
  asyncLoad?: boolean;
  /**
   * 是否支持搜索
   * @default true
   */
  showSearch?: boolean;
  /**
   * 是否使用勾选框多选模式
   * @default false
   */
  checkable?: boolean;
  /**
   * 是否显示全选按钮
   * @default true
   */
  showCheckAll?: boolean;
  /**
   * 勾选框模式下，父子节点是否关联
   * @default true
   */
  checkStrictly?: boolean;
  /**
   * 显示策略，决定回填选择框的内容
   * @default 'SHOW_CHILD'
   */
  showCheckedStrategy?: "SHOW_ALL" | "SHOW_PARENT" | "SHOW_CHILD";
}

/**
 * 组织人员选择树组件
 */
const OrganizationTreeSelect: React.FC<OrganizationTreeSelectProps> = ({
  fetchRootData,
  loadChildrenData,
  showUserInfo = true,
  userOnly = true,
  initialData,
  loading: externalLoading,
  asyncLoad = false,
  showSearch = true,
  checkable = false, // 默认不使用勾选框
  showCheckAll = true,
  checkStrictly = false, // 默认父子节点关联
  multiple = false,
  showCheckedStrategy = "SHOW_CHILD", // 默认只显示子节点
  ...restProps
}) => {
  const [treeData, setTreeData] = useState<OrgTreeNode[]>(initialData || []);
  const [loading, setLoading] = useState(false);
  const [checkedAll, setCheckedAll] = useState(false);

  // 加载组织数据
  useEffect(() => {
    if (initialData?.length) {
      // 如果提供了初始数据，则使用初始数据
      return;
    }

    const fetchData = async () => {
      if (!fetchRootData) return;

      setLoading(true);
      try {
        const data = await fetchRootData();

        // 如果启用异步加载，标记非叶子节点为异步加载对象
        if (asyncLoad && loadChildrenData) {
          const processNodes = (nodes: OrgTreeNode[]): OrgTreeNode[] => {
            return nodes.map((node) => ({
              ...node,
              isLeaf: node.type === "user", // 用户节点是叶子节点
              children: node.children ? processNodes(node.children) : undefined,
            }));
          };
          setTreeData(processNodes(data));
        } else {
          setTreeData(data);
        }
      } catch (error) {
        console.error("Failed to load organization data:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [fetchRootData, initialData, asyncLoad, loadChildrenData]);

  // 处理异步加载子节点
  const handleLoadData = async (node: any): Promise<void> => {
    if (
      !asyncLoad ||
      !loadChildrenData ||
      (node.children && node.children.length > 0)
    ) {
      return Promise.resolve();
    }

    return new Promise<void>(async (resolve) => {
      try {
        const children = await loadChildrenData(node);
        // 异步加载时也需要处理节点属性
        const processedChildren = children.map((child) => ({
          ...child,
          isLeaf: child.type === "user", // 用户节点是叶子节点
        }));

        // 更新节点的子节点
        setTreeData((prevTreeData) => {
          const updateTreeNode = (nodes: OrgTreeNode[]): OrgTreeNode[] => {
            return nodes.map((n) => {
              if (n.key === node.key) {
                return { ...n, children: processedChildren };
              }
              if (n.children) {
                return { ...n, children: updateTreeNode(n.children) };
              }
              return n;
            });
          };
          return updateTreeNode(prevTreeData);
        });
        resolve();
      } catch (error) {
        console.error("Failed to load children:", error);
        resolve();
      }
    });
  };

  // 自定义节点渲染
  const titleRender = (nodeData: OrgTreeNode) => {
    if (nodeData.type === "user" && showUserInfo) {
      return (
        <div className="org-tree-user-node">
          {nodeData.avatar && (
            <img
              src={nodeData.avatar}
              alt={nodeData.title}
              className="org-tree-user-avatar"
            />
          )}
          <div className="org-tree-user-info">
            <span className="org-tree-user-name">{nodeData.title}</span>
            {nodeData.position && (
              <span className="org-tree-user-position">
                {nodeData.position}
              </span>
            )}
          </div>
        </div>
      );
    }

    // 组织/部门节点
    return (
      <span className={`org-tree-${nodeData.type}-node`}>{nodeData.title}</span>
    );
  };

  // 处理节点，设置非用户节点为禁用状态
  const processNode = (node: OrgTreeNode, userOnly: boolean): OrgTreeNode => {
    const newNode = { ...node };
    if (userOnly && node.type !== "user") {
      newNode.disabled = true;
    }

    if (node.children) {
      newNode.children = node.children.map((child) =>
        processNode(child, userOnly)
      );
    }

    return newNode;
  };

  // 过滤节点，如果 userOnly=true，则只能选择用户节点
  const treeDataWithDisabled = userOnly
    ? treeData.map((node) => processNode(node, userOnly))
    : treeData;

  // 处理全选
  const handleCheckAll = () => {
    if (!checkedAll) {
      // 获取所有可选节点的值
      const getAllValues = (nodes: OrgTreeNode[]): string[] => {
        let values: string[] = [];
        nodes.forEach((node) => {
          if (!node.disabled) {
            values.push(node.value);
          }
          if (node.children?.length) {
            values = [...values, ...getAllValues(node.children)];
          }
        });
        return values;
      };

      const allValues = getAllValues(treeDataWithDisabled);
      if (restProps.onChange) {
        restProps.onChange(allValues, null);
      }
      setCheckedAll(true);
    } else {
      // 清空选择
      if (restProps.onChange) {
        restProps.onChange([], null);
      }
      setCheckedAll(false);
    }
  };

  // 当选择变化时更新全选状态
  useEffect(() => {
    if (checkable && showCheckAll && Array.isArray(restProps.value)) {
      // 获取所有可选节点的数量
      const getSelectableCount = (nodes: OrgTreeNode[]): number => {
        let count = 0;
        nodes.forEach((node) => {
          if (!node.disabled) {
            count++;
          }
          if (node.children?.length) {
            count += getSelectableCount(node.children);
          }
        });
        return count;
      };

      const totalSelectable = getSelectableCount(treeDataWithDisabled);
      setCheckedAll(restProps.value?.length === totalSelectable);
    }
  }, [restProps.value, treeDataWithDisabled, checkable, showCheckAll]);

  // 自定义标签渲染函数
  const tagRender = (props: any) => {
    const { label, value, closable, onClose } = props;

    // 查找对应的节点数据
    const findNodeByValue = (
      nodes: OrgTreeNode[],
      val: string
    ): OrgTreeNode | null => {
      for (const node of nodes) {
        if (node.value === val) return node;
        if (node.children) {
          const found = findNodeByValue(node.children, val);
          if (found) return found;
        }
      }
      return null;
    };

    const node = findNodeByValue(treeData, value as string);

    if (!node) {
      return (
        <Tag
          closable={closable}
          onClose={onClose}
          className="org-tree-tag default-tag"
        >
          {label}
        </Tag>
      );
    }

    let tagClass = "org-tree-tag";
    let tagContent = label;

    // 根据节点类型自定义标签样式和内容
    switch (node.type) {
      case "user":
        tagClass += " user-tag";
        tagContent = (
          <div className="user-tag-content">
            {node.avatar && showUserInfo && (
              <img src={node.avatar} alt="" className="tag-user-avatar" />
            )}
            <span>{label}</span>
            {node.position && showUserInfo && (
              <span className="tag-user-position">{node.position}</span>
            )}
          </div>
        );
        break;
      case "department":
        tagClass += " department-tag";
        break;
      case "org":
        tagClass += " org-tag";
        break;
      default:
        break;
    }

    return (
      <Tag closable={closable} onClose={onClose} className={tagClass}>
        {tagContent}
      </Tag>
    );
  };

  return (
    <Spin spinning={loading || !!externalLoading}>
      <div className="organization-tree-select-wrapper">
        {checkable && showCheckAll && (
          <div className="check-all-row">
            <label className="check-all-label">
              <input
                type="checkbox"
                checked={checkedAll}
                onChange={handleCheckAll}
              />
              <span>全选</span>
            </label>
          </div>
        )}
        <TreeSelect
          className="organization-tree-select"
          treeData={treeDataWithDisabled}
          placeholder="请选择组织或人员"
          treeDefaultExpandAll={!asyncLoad} // 异步加载时不自动展开所有节点
          showSearch={showSearch}
          filterTreeNode={(inputValue, treeNode) => {
            return (treeNode.title as string)
              .toLowerCase()
              .includes(inputValue.toLowerCase());
          }}
          treeNodeFilterProp="title"
          titleRender={titleRender}
          tagRender={tagRender}
          multiple={multiple || checkable}
          treeCheckable={checkable}
          showCheckedStrategy={
            checkable ? TreeSelect[showCheckedStrategy] : undefined
          }
          treeCheckStrictly={checkStrictly}
          loadData={asyncLoad ? handleLoadData : undefined}
          {...restProps}
        />
      </div>
    </Spin>
  );
};

export default OrganizationTreeSelect;
